package org.darkforest.controller;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.darkforest.auth.AuthPassport;
import org.darkforest.auth.CurrentMember;
import org.darkforest.common.services.CartService;
import org.darkforest.common.services.OrderService;
import org.darkforest.common.services.SimpleRedisService;
import org.darkforest.common.services.SmsService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.wxpay.payutils.MD5Util;
import org.darkforest.common.wxpay.payutils.Sha1Util;
import org.darkforest.common.wxpay.utils.HttpTool;
import org.darkforest.common.wxpay.utils.XMLUtil;
import org.darkforest.dao.mapper.CartMapper;
import org.darkforest.dao.mapper.CountySupportPoorMapper;
import org.darkforest.dao.mapper.EnumParamMapper;
import org.darkforest.dao.mapper.StoreMapper;
import org.darkforest.enums.MemberType;
import org.darkforest.enums.SettingNameEnum;
import org.darkforest.model.*;
import org.darkforest.service.TokenService;
import org.darkforest.ucenter.service.AddressService;
import org.darkforest.ucenter.service.MemberService;
import org.darkforest.vo.MemberBase;
import org.darkforest.vo.MemberDataStatisticsVo;
import org.darkforest.vo.WapAjaxMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @auth bingo
 * @create 2017-09-22-18:04
 */
@RestController
@RequestMapping(value = "member")
@Api(value = "member", description = "用户", produces = MediaType.APPLICATION_JSON_VALUE)
public class MemberController {

    Logger logger = LoggerFactory.getLogger(MemberController.class);

    @Autowired
    @Qualifier("wapMemberServiceImpl")
    private MemberService memberService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private AddressService addressService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private EnumParamMapper enumParamMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private SimpleRedisService simpleRedisService;
    @Autowired
    private CountySupportPoorMapper countySupportPoorMapper;

    @RequestMapping(value = "loginTest", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录测试", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity loginTest(@RequestParam(required = true) String mobile, @RequestParam(required = true) String code) {
//        try {
//            Member condition = new Member();
//            condition.setMemberMobile(mobile);
//            List<Member> list = memberService.findByCondition(condition);
//            if (list.size() > 0) {
//                boolean res = smsService.verfiyCaptcha(mobile, code);
//                if (!res) {
//                    return RestEntity.failed("验证码错误");
//                } else {
//                    Token token = tokenService.createToken(list.get(0).getMemberId());
        Token token = tokenService.createToken(10130);
        return RestEntity.success(token);
//                }
//            } else {
//                return RestEntity.failed("该账号不存在");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return RestEntity.failed("登录异常");
//        }
    }

    /**
     *  用户登陆
     *
     * @param memberName
     * @param memberPasswd
     * @param mobile
     * @param code
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity login(@RequestParam(required = false, defaultValue = "") String memberName,
                            @RequestParam(required = false, defaultValue = "") String memberPasswd,
                            @RequestParam(required = false, defaultValue = "") String mobile,
                            @RequestParam(required = false, defaultValue = "") String code) {
        try {

//            logger.info("************************************************testWeixinApitestMch  start");
//            logger.info("************************************************testWeixinApitestMch  start");
//            testWeixinApitestMch();
//            logger.info("************************************************testWeixinApitestMch  end");
//            logger.info("************************************************testWeixinApitestMch  end");

            logger.info("memberName="+memberName+"  memberPasswd=*******  mobile="+mobile);
            // 用户名、密码登录的场合
            if (!StringUtils.isEmpty(memberName) && !StringUtils.isEmpty(memberPasswd)) {
                Member memberDb = memberService.getBaseMemberInfo(memberName);
                if (memberDb == null) {
                    return RestEntity.failed("输入的用户名不存在，请确认是否已注册");
                }

                // 登录成功时
                if (DigestUtils.md5Hex(memberPasswd).equals(memberDb.getMemberPasswd())) {
                    //更新登陆时间、登陆次数
                    Member member = new Member();
                    member.setMemberId(memberDb.getMemberId());
                    member.setMemberOldLoginTime(memberDb.getMemberLoginTime() != null ? memberDb.getMemberLoginTime() : "");
                    member.setMemberLoginTime(DateUtil.unixTimeStamp());
                    member.setMemberLoginNum(memberDb.getMemberLoginNum() != null ? memberDb.getMemberLoginNum() + 1 : 1);
                    memberService.updateMemberBaseInfo(member);

                    Token token = tokenService.createToken(memberDb.getMemberId());
                    return RestEntity.success(token);
                } else {
                    return RestEntity.failed("输入的密码不正确，请重新输入");
                }
            }

            // 快捷登录的场合
            if (!StringUtils.isEmpty(mobile) && !StringUtils.isEmpty(code)) {
                if ("0000".equals(code)) {
                    // 测试时默认用验证码
                } else {
                    // 验证码CHECK
                    boolean res = smsService.verfiyCaptcha(mobile, code);
                    if (!res) {
                        return RestEntity.failed("手机验证码错误，请重新输入");
                    }

                    /*****清除缓存验证码*****/
                    simpleRedisService.deleteByKey(mobile);
                }

                // 根据手机号登录
                Member condition = new Member();
                condition.setMemberMobile(mobile);
                List<Member> list = memberService.findByCondition(condition);

                // 数据库有的场合、登录处理
                if (list.size() > 0) {
                    //更新登陆时间、登陆次数
                    Member member = new Member();
                    member.setMemberId(list.get(0).getMemberId());
                    member.setMemberOldLoginTime(list.get(0).getMemberLoginTime() != null ? list.get(0).getMemberLoginTime() : "");
                    member.setMemberLoginTime(DateUtil.unixTimeStamp());
                    member.setMemberLoginNum(list.get(0).getMemberLoginNum() != null ? list.get(0).getMemberLoginNum() + 1 : 1);
                    memberService.updateMemberBaseInfo(member);

                    Token token = tokenService.createToken(list.get(0).getMemberId());
                    return RestEntity.success(token);
                } else {

                    // 领取礼品时，下一步（登录）即为注册
                    Member member = new Member();
                    member.setMemberName(mobile);
                    member.setMemberPasswd("123456");   // 密码为非空项目
                    member.setMemberPasswdConfirm("123456");
                    member.setMemberMobile(mobile);
                    member.setMemberMobileBind(1);
                    member.setCompanyId(0);     // 自动注册时CompanyId设为0
                    member.setMemberTypeEnum(MemberType.NORMAL);   //  只是领取礼品时，不能设为会员, 登录后才可设为会员？？？
                    WapAjaxMsg<MemberBase> mb = memberService.regist(member);

                    Token token = tokenService.createToken(mb.getDatas().getUserId());
                    return RestEntity.success(token);
                }
            }
            // 账号/密码登录、手机号/验证码 登录 以外的登录条件（暂无）
            return RestEntity.failed("登录条件错误，请确认处理是否正确");
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("登录异常");
        }
    }

    /***
     * 用户注册
     *
     * @param member
     * @param memberPasswd
     * @return
     */
    @RequestMapping(value = "regist", method = RequestMethod.POST)
    @ApiOperation(value = "用户注册", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity regist(@RequestBody Member member, @RequestParam(required = false, defaultValue = "") String memberPasswd) {
        try {
            // 通过member.memberPasswd设定时，此处取不到值
            member.setMemberPasswd(memberPasswd);
            member.setMemberPasswdConfirm(memberPasswd);

            // 手机号、手机验证码、邮箱验证码都没有 , 符号
            String memberMobile = member.getMemberMobile();
            String memberEmail = member.getMemberEmail();

            // 公司会员注册
            if (member.getCompanyId() != 0) {
                if (StringUtils.isEmpty(memberMobile) || StringUtils.isEmpty(memberEmail)) {
                    return RestEntity.failed("手机号和邮箱都不能为空");
                }

                if ((memberMobile.indexOf(",") < 1) || (memberEmail.indexOf(",")  < 1)) {
                    return RestEntity.failed("手机号和邮箱都不能为空");
                }
            } else {
                if (StringUtils.isEmpty(memberMobile) || (memberMobile.indexOf(",") < 1)) {
                    return RestEntity.failed("手机号不能为空");
                }
            }

            String mobile = memberMobile.split(",")[0];
            String mobileCode = memberMobile.split(",")[1];

            // 验证手机号是否已注册过
            Member memberTemp = new Member();
            memberTemp.setMemberMobile(mobile);
            List<Member> list = memberService.getMemberByCond(memberTemp);
            if (list.size() > 0) {
                return RestEntity.failed("该手机号已注册，请选择其他手机号");
            }

            // 公司会员注册
            if (member.getCompanyId() != 0) {
                // 邮箱的@的后面都没有 , 符号
                String email = memberEmail.split(",")[0];
                String emailCode = memberEmail.split(",")[1];

                // 验证邮箱是否已注册过
                memberTemp = new Member();
                memberTemp.setMemberEmail(email);
                list = memberService.getMemberByCond(memberTemp);
                if (list.size() > 0) {
                    return RestEntity.failed("该邮箱已注册，请选择其他邮箱");
                }

                //  验证码CHECK
                Boolean res1 = smsService.verfiyCaptcha(email, emailCode);
                Boolean res2 = smsService.verfiyCaptcha(mobile, mobileCode);
                if (res1 && res2) {
                    // memberName、memberPasswd、memberPasswdConfirm、companyId  从页面上设置
                    // memberMobile、memberEmail需要重新设置
                    member.setMemberMobile(mobile);
                    member.setMemberMobileBind(1);
                    member.setMemberEmail(email);
                    member.setMemberEmailBind(1);
                    member.setMemberTypeEnum(MemberType.EMPLOYEE);

                    WapAjaxMsg<MemberBase> msg = memberService.regist(member);

                    /*****清除缓存验证码*****/
                    simpleRedisService.deleteByKey(email);
                    simpleRedisService.deleteByKey(mobile);

                    if (!StringUtils.isEmpty(msg.getError())) {
                        return RestEntity.failed(msg.getError());
                    } else {
                        return RestEntity.success("注册成功");
                    }
                } else if (!res1) {
                    return RestEntity.failed("邮箱验证码有误，请重新输入");
                } else if(!res2){
                    return RestEntity.failed("手机验证码错误，请重新输入");
                } else {
                    return RestEntity.failed("手机验证码与邮箱验证码有误，请重新输入");
                }
            } else {
                // 非公司会员注册
                //  验证码CHECK
                Boolean res = smsService.verfiyCaptcha(mobile, mobileCode);
                if (res) {
                    // memberName、memberPasswd、memberPasswdConfirm、companyId 从页面上设置
                    // memberMobile、memberEmail需要重新设置
                    member.setMemberMobile(mobile);
                    member.setMemberMobileBind(1);
                    member.setMemberEmail(null);
                    member.setMemberEmailBind(0);
                    member.setMemberTypeEnum(MemberType.NORMAL);

                    WapAjaxMsg<MemberBase> msg = memberService.regist(member);

                    /*****清除缓存验证码*****/
                    simpleRedisService.deleteByKey(mobile);

                    if (!StringUtils.isEmpty(msg.getError())) {
                        return RestEntity.failed(msg.getError());
                    } else {
                        return RestEntity.success("注册成功");
                    }
                } else {
                    return RestEntity.failed("手机验证码有误，请重新输入");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("注册异常");
        }
    }

    /**
     * 手机、邮箱验证码的取得
     *
     * @param channel
     * @param type
     * @return
     */
    @RequestMapping(value = "sendCode", method = RequestMethod.GET)
    @ApiOperation(value = "发送邮箱或者手机验证 type（0 手机、1 邮箱）", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity sendCode(@RequestParam(required = true) String channel, @RequestParam(required = false, defaultValue = "0") String type) {
        try {
            if (!StringUtils.isEmpty(channel) && type.equals("0")) {
                smsService.sendCaptcha(channel, 1800);
            } else if (!StringUtils.isEmpty(channel) && type.equals("1")) {
                smsService.sendMailCode(channel, 1800);
            }
            return RestEntity.success("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("发送异常");
        }
    }

    /**
     *  找回密码
     *
     * @param memberPasswd
     * @param mobile
     * @param code
     * @return
     */
    @RequestMapping(value = "updateMemberPasswd", method = RequestMethod.POST)
    @ApiOperation(value = "用户找回密码", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity updateMemberPasswd(@RequestParam(required = false, defaultValue = "") String memberPasswd,
                                         @RequestParam(required = false, defaultValue = "") String mobile,
                                         @RequestParam(required = false, defaultValue = "") String code) {

        try {
            // 验证码CHECK
            Boolean res = smsService.verfiyCaptcha(mobile, code);
            if (!res) {
                return RestEntity.failed("手机验证码有误，请重新输入");
            }

            // 验证手机号是否已注册过
            Member memberTemp = new Member();
            memberTemp.setMemberMobile(mobile);
            List<Member> list = memberService.getMemberByCond(memberTemp);
            if (list.size() == 0) {
                return RestEntity.failed("该手机号还没有注册过，请重新输入");
            }

            // 更新密码
            Member member = new Member();
            member.setMemberId(list.get(0).getMemberId());
            member.setMemberPasswd(DigestUtils.md5Hex(memberPasswd));
            memberService.updateMemberBaseInfo(member);
            return RestEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("找回密码异常");
        }
    }

    /**
     * 用户详细资料
     *
     * @return
     */
    @RequestMapping(value = "memberDetail", method = RequestMethod.GET)
    @AuthPassport
    @ApiOperation(value = "用户基本信息", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity memberDetail(@CurrentMember Member member) {
        try {
            MemberWithBLOBs memberWithBLOBs = memberService.findMemberById(member.getMemberId());
            return RestEntity.success(memberWithBLOBs);
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("获取异常");
        }
    }

    /**
     * 用户绑定邮箱或者修改邮箱
     *
     * @param member
     * @param email
     * @return
     */
    @RequestMapping(value = "bindMemberEmail", method = RequestMethod.POST)
    @AuthPassport
    @ApiOperation(value = "用户绑定邮箱或者修改邮箱", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity bindMemberEmail(@CurrentMember Member member, String email) {

        MemberWithBLOBs memberWithBLOBs = new MemberWithBLOBs();
        memberWithBLOBs.setMemberId(member.getMemberId());
        memberWithBLOBs.setMemberEmail(email);
        memberWithBLOBs.setMemberEmailBind(1);
        memberService.updateMember(memberWithBLOBs);
        return RestEntity.success();
    }

    /**
     *  个人统计
     *
     * @param member
     * @return
     */
    @AuthPassport
    @RequestMapping(value = "statistics", method = RequestMethod.GET)
    @ApiOperation(value = "个人统计", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity statistics(@CurrentMember Member member) {
        try {
            MemberDataStatisticsVo mv = new MemberDataStatisticsVo();
            //购物车商品个数
            Integer goodsNum = cartMapper.countCartNumberByMemberId(member.getMemberId());
            mv.setCartGoodsNum(goodsNum);

            //常用地址个数
            List<Address> list = addressService.getAddressList(member.getMemberId());
            mv.setAddressNum(list.size());

            //未支付订单个数
            Order param = new Order();
            param.setBuyerId(member.getMemberId());
            param.setPageSwitch(false);
            param.setOrderState("10");
            List<Order> orderList = orderService.findOrderWithGoodsByCondition(param);
            mv.setUnPayOrderNum(orderList.size());
            return RestEntity.success(mv);
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed();
        }
    }

    /**
     * 贫困县或企业取得
     *
     * @param paramType
     * @return
     */
    @RequestMapping(value = "countryorcompany", method = RequestMethod.GET)
    @ApiOperation(value = "贫困县或企业接口,参数默认county:贫困县，company：企业", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity countryOrCompany(@RequestParam(required = false, defaultValue = "county") String paramType) {
        try {
//            EnumParam enumParam = new EnumParam();
//            enumParam.setPageSwitch(false);
//            enumParam.setParamType(paramType);
//            enumParam.setParamState(1);
//            List<EnumParam> list = enumParamMapper.selectListByCondition(enumParam);
            List<EnumParam> list = new ArrayList<EnumParam>();
            if ("county".equals(paramType)){
                CountySupportPoor countySupportPoor = new CountySupportPoor();
                countySupportPoor.setPageSwitch(false);
                List<CountySupportPoor> countySupportPoorList = countySupportPoorMapper.selectListByCondition(countySupportPoor);
                for(CountySupportPoor county : countySupportPoorList){
                    EnumParam enumParam = new EnumParam();
                    enumParam.setParamId(county.getCountyId());
                    enumParam.setParamType("county");
                    enumParam.setParamKey(county.getCountyName());
                    // 西藏 山南地区 洛扎县  --->>  西藏洛扎县
                    String area1 = county.getCountyArea();
                    String[] area2 = area1.split(" ");
                    String area3 = area2[0] + area2[area2.length-1];
                    enumParam.setParamValue(area3);
                    enumParam.setParamState(1);
                    list.add(enumParam);
                }
            }else{
                EnumParam enumParam = new EnumParam();
                enumParam.setPageSwitch(false);
                enumParam.setParamType(paramType);
                enumParam.setParamState(1);
                list = enumParamMapper.selectListByCondition(enumParam);
            }
            return RestEntity.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed();
        }
    }

    /**
     * 退出登陆
     *
     * @param member
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ApiOperation(value = "用户退出", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity logout(@CurrentMember Member member) {
        try {
            boolean res = tokenService.delToken(member.getMemberId());
            if (res)
                return RestEntity.success("退出成功");
            else
                return RestEntity.failed("退出失败");
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("退出异常");
        }
    }

    /***
     * 邮箱或者手机验证
     *
     * @param channel
     * @param type
     * @return
     */
    @RequestMapping(value = "validateChannel", method = RequestMethod.GET)
    @ApiOperation(value = "验证邮箱或者手机验证是否已注册 type（0 手机、1 邮箱） 返回值 01 已注册 02 未注册", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity validateChannel(@RequestParam(required = true) String channel, @RequestParam(required = false, defaultValue = "0") String type) {
        try {
            List<Member> list = new ArrayList<Member>();
            Member member = new Member();
            if (!StringUtils.isEmpty(channel) && type.equals("0")) {
                member.setMemberMobile(channel);
                list = memberService.getMemberByCond(member);
            } else if (!StringUtils.isEmpty(channel) && type.equals("1")) {
                member.setMemberEmail(channel);
                list = memberService.getMemberByCond(member);
            }
            if (list.size() > 0) {
                return RestEntity.success("01");
            } else {
                return RestEntity.success("02");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("验证异常");
        }
    }

    @RequestMapping(value = "verfiyCode", method = RequestMethod.GET)
    @ApiOperation(value = "验证手机或邮箱验证码是否正确 type（0 手机、1 邮箱）", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_VALUE)
    public RestEntity verfiyCode(@RequestParam(required = true) String channel, @RequestParam(required = true) String code) {
        try {
            Boolean res = smsService.verfiyCaptcha(channel, code);
            if (res) {
                return RestEntity.success("验证码正确");
            } else {
                return RestEntity.failed("验证码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestEntity.failed("验证异常");
        }
    }

    private void testWeixinApitestMch() {

        try {
            String nonceStr = Sha1Util.getNonceStr();//随机字符串
            TreeMap<String, String> contentMap1 = new TreeMap<String, String>();
            //contentMap1.put("appid", "wxe39cbe60cfe8ad76"); // 公众账号 ID
            contentMap1.put("mch_id", "1493907282"); // 商户号   1492506782（测试环境）
            contentMap1.put("nonce_str", nonceStr); // 随机字符串
            //String wxpackage = createPackage(contentMap);
            //String string1 = originalString(contentMap);
            Set<Map.Entry<String, String>> entry = contentMap1.entrySet();
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> obj : entry) {
                String k = obj.getKey();
                String v = obj.getValue();
                if (v == null && v.equals(""))
                    continue;
                sb.append(k + "=" + v + "&");
            }
            String string1 = sb.toString();
            logger.info("originalString="+string1);
            String stringSignTemp = string1 + "key=436152a9f9cf0762fe10d0187c032289";  // a446c01a6d33bfcb8a0d601f58e33988(测试环境)
            String sign = MD5Util.MD5Encode(stringSignTemp, "UTF-8").toUpperCase();
            logger.info("sign="+sign);

            TreeMap<String, String> contentMap = new TreeMap<String, String>();
            contentMap.put("mch_id", "1493907282"); // 商户号
            contentMap.put("nonce_str", nonceStr); // 随机字符串
            contentMap.put("sign", sign);

            String result = HttpTool.sendPost("https://apitest.mch.weixin.qq.com/sandboxnew/pay/getsignkey", contentMap, "UTF-8");
            Map<String, String> temp = XMLUtil.doXMLParse(result);//调用统一接口返回的值转换为XML格式
            // {return_msg=ok, sandbox_signkey=00c124c83a5125c572c7b9ed1f7518b5, return_code=SUCCESS}
            System.out.println(temp);
            logger.info("return_code="+temp.get("return_code"));
            logger.info("return_msg="+temp.get("return_msg"));
        } catch (Exception e) {
            logger.info("Exception="+e.getMessage());
            e.printStackTrace();
        }
    }
}